package com.sky.com.admin.service.impl;

import cn.hutool.jwt.JWT;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.sky.com.admin.entity.Admin;
import com.sky.com.admin.entity.DTO.AdminLoginDTO;
import com.sky.com.admin.exception.NonloginException;
import com.sky.com.admin.mapper.AdminMapper;
import com.sky.com.admin.service.AdminService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sky.com.admin.utils.BCryptPasswordEncoder;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.nio.charset.StandardCharsets;

/**
 * <p>
 * 管理员表 服务实现类
 * </p>
 *
 * @author wuyunbin
 * @since 2022-12-08
 */
@Slf4j
@Service
public class AdminServiceImpl extends ServiceImpl<AdminMapper, Admin> implements AdminService {
@Autowired
private  AdminMapper adminMapper;
@Autowired
private BCryptPasswordEncoder bCryptPasswordEncoder;
private  String key="123456";

    @Override
    public String adminLogin(AdminLoginDTO adminLoginDTO) {
        //判断数据库中是否存在dto对象
        LambdaQueryWrapper<Admin> wrapper = new LambdaQueryWrapper<>();
         wrapper.eq(Admin::getEmail, adminLoginDTO.getEmail());
        Admin one = adminMapper.selectOne(wrapper);
        //显示加密密码

        log.info("密码是：{}",bCryptPasswordEncoder.encode(adminLoginDTO.getPassword()));
        if (null==one){
            //不存在
            //报错
            throw new NonloginException("邮箱不存在！");
        }
        //存在，判断密码是否正确
        //明文密码  数据库密码
        boolean result = bCryptPasswordEncoder.matches(adminLoginDTO.getPassword(), one.getPassword());
        if (result = true) {
            //正确，输出
            log.info("{}", "登陆成功！");
            //签发token
            String token = JWT.create().setPayload("adminId", one.getAdminId())
                    .setPayload("time", System.currentTimeMillis())//迷惑信息，为了每次生成token不一样
                    .setKey(key.getBytes(StandardCharsets.UTF_8))
                    .sign();
            return token;
        }
        throw new NonloginException("密码错误！");
        }
    }

